#include "Acceptor.h"
#include "log/Log.h"

namespace net
{

Acceptor::Acceptor(EventLoop::ptr ptrEventLoop, IPAddress::ptr ptrAddr)
    : m_ptrEventLoop(ptrEventLoop)
{
    m_ptrSock = Socket::createTcpIPv4Socket();
    if (!m_ptrSock->bind(ptrAddr))
    {
        return;
    }

    if (m_ptrSock->listen())
    {
        SYS_FMT_INFO("server start listen addr %s", ptrAddr->getIpPort().c_str());
    }
}

Acceptor::~Acceptor()
{
}


void Acceptor::startAccept()
{
    m_ptrChannel = std::make_shared<Channel>(m_ptrSock);
    m_ptrChannel->addListenEvent(EPOLLIN | EPOLLET);
    m_ptrChannel->setEventCallback(std::bind(&Acceptor::handleEvent, this));
    m_ptrEventLoop->updateChannel(m_ptrChannel);
}

void Acceptor::setNewConnectionCB(std::function<void(Socket::ptr)> cb)
{
    m_newConnectionCB = cb;
}

void Acceptor::handleEvent()
{
    IPAddress::ptr addr;
    Socket::ptr clientSock = m_ptrSock->accept(addr);
    if (!clientSock)
    {
        SYS_ERROR() << "socket accept errro";
        return;
    }
    clientSock->setNonBlocking();
    m_newConnectionCB(clientSock);
}

} // namespace net
